package com.gitee.farmer.im.service;

import com.alibaba.fastjson.JSONObject;
import com.gitee.farmer.im.entity.FarmerMessage;
import com.gitee.farmer.im.repository.FarmerMessageRepository;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * @author dong.chengsong
 * @ClassName: FarmerMessageService
 * @Description: (这里用一句话描述这个类的作用)
 * @date 2022/3/1 13:03
 */
@Service
public class FarmerMessageService {

    private final FarmerMessageRepository farmerMessageRepository;

    public FarmerMessageService(FarmerMessageRepository farmerMessageRepository) {
        this.farmerMessageRepository = farmerMessageRepository;
    }

    public FarmerMessage save(JSONObject jsonTo){
        FarmerMessage message = new FarmerMessage();
        message.setType(getStringWithDefault(jsonTo,"type",""));
        message.setFromUser(getStringWithDefault(jsonTo,"from",""));
        message.setToUser(getStringWithDefault(jsonTo,"to",""));
        message.setContext(getStringWithDefault(jsonTo,"text",""));
        message.setUrl(getStringWithDefault(jsonTo,"url",""));
        message.setLat(getStringWithDefault(jsonTo,"lat",""));
        message.setLng(getStringWithDefault(jsonTo,"lng",""));
        final Date createTime = new Date();
        message.setCreateTime(createTime);
        message.setReadTime(createTime);
        message.setReadState(0);
        return farmerMessageRepository.save(message);
    }

    private String getStringWithDefault(JSONObject jsonTo,String key,String defaultVal){
        final String str = jsonTo.getString(key);
        return str == null ? defaultVal:str;
    }
}
